﻿Imports System.Runtime.InteropServices

Namespace OpenCL
    ''' <summary>
    ''' バッファー
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Buffer
        Public Property InternalPointer() As IntPtr
            Get
                Return m_InternalPointer
            End Get
            Private Set(ByVal value As IntPtr)
                m_InternalPointer = value
            End Set
        End Property
        Private m_InternalPointer As IntPtr
        Public Property SizeInBytes() As Integer
            Get
                Return m_SizeInBytes
            End Get
            Private Set(ByVal value As Integer)
                m_SizeInBytes = value
            End Set
        End Property
        Private m_SizeInBytes As Integer

        Private Sub New()
        End Sub

        Protected Overrides Sub Finalize()
            Try
                OpenCLAPI.clReleaseMemObject(InternalPointer)
            Finally
                MyBase.Finalize()
            End Try
        End Sub

        Public Shared Function FromCopiedHostMemory(Of T As Structure)(ByVal context As Context, ByVal initialData As T()) As Buffer
            Dim result As New Buffer()
            result.SizeInBytes = Marshal.SizeOf(GetType(T)) * initialData.Length

            Dim errorCode As Integer
            Dim handle As GCHandle = GCHandle.Alloc(initialData, GCHandleType.Pinned)

            result.InternalPointer = OpenCLAPI.clCreateBuffer(context.InternalPointer, MemoryFlags.CopyHostMemory, result.SizeInBytes, handle.AddrOfPinnedObject(), errorCode)

            handle.Free()
            Return result
        End Function
    End Class
End Namespace